// console.log(1);

// 逻辑分析：
//  1获取元素
/*  2获取数据 
        +渲染数据
        +根据数据进行分页
    3点击分页按钮 去获取对应页的数据
        +在发送ajax请求
*/
let list = document.querySelector('.list');
let page = document.querySelector('.page');
let obj = {
    index: 1,
    len: 20
}
// 第一次获取数据（渲染结构和分页渲染）
pAjax({
    url: '../api/getData.php',
    data: {
        index: obj.index,
        len: obj.len
    }
}).then(res => {
    // console.log(res);
    res = JSON.parse(res);
    // console.log(res);
    render(res.list);
    new Pagination(page, {
        pageInfo: {
            pagenum: 1,
            pagesize: obj.len,
            total: res.total,
            totalpage: Math.ceil(res.total / obj.len) // 页码总数
        },
        textInfo: {
            first: '首页',
            prev: '上一页',
            list: '',
            next: '下一页',
            last: '尾页'
        },
        change: function (index) {
          obj.index = index;
          getDate();
        }
    });
});

async function getDate() {
    let res = await pAjax({
        url: '../api/getData.php',
        data: {
            index: obj.index,
            len: obj.len
        },
    });
    res = JSON.parse(res);
    render(res.list);
    scrollTo({top:0});
}

function render(data) {
    let str = '';
    data.forEach((item, index) => {
        // console.log(item);
        str += ` <li class="list-item">
        <div class="title">
            <ol class="breadcrumb">
                <li><a href="#">${item.cat_one_id}</a></li>
                <li><a href="#">${item.cat_two_id}</a></li>
                <li class="active">${item.cat_three_id}</li>
            </ol>
        </div>
        <div class="row">
            <div>
                <div class="thumbnail">
                    <img
                        src="${item.goods_big_logo}"
                        alt="..."
                    />
                    <div class="caption">
                        <h3>
                           ${item.goods_name}
                        </h3>
                        <div class="price">
                            <i class="glyphicon glyphicon-yen"></i>
                            <span>${item.goods_price}</span>
                        </div>
                        <p>
                            <a
                                href="./car.html"
                                class="btn btn-primary"
                                role="button"
                            >
                                查看购物车
                            </a>
                            <a
                                href="./detail.html?id=${item.goods_id}"
                                class="btn btn-info"
                                role="button"
                            >
                                查看商品详情
                            </a>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </li>`;
    });
    list.innerHTML = str;

}